//
//  ModelViewController.m
//  MZJ
//
//  Created by XDD on 16/6/6.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "ModelViewController.h"
#import "StandViewController.h"

@interface ModelViewController ()

@end

@implementation ModelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)userInfo_data_save:(NSString *)fileName_Str responseObject:(id)responseObject {
    NSString *sandBoxPath = NSHomeDirectory();
    NSString * documentPath = [sandBoxPath stringByAppendingPathComponent:@"Documents"];
    NSString *newFielPath2 = [documentPath stringByAppendingPathComponent:fileName_Str];
    NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:0 error:nil];
    [data writeToFile:newFielPath2 options:0 error:nil];
//    NSLog(@"%@",newFielPath2);
}

- (NSDictionary *)userInfo_data_get: (NSString *)fileName_Str {
    NSString * sandBoxPath = NSHomeDirectory();
    NSString * documentPath = [sandBoxPath stringByAppendingPathComponent:@"Documents"];
    NSString * filename = [documentPath stringByAppendingPathComponent:fileName_Str];
    NSData *data = [NSData dataWithContentsOfFile:filename options:0 error:NULL];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//    NSLog(@"%@",dic);
    
    return dic;
}

-(NSString *)TimeStamp:(NSString *)strTime form_time:(NSString *)form_time{

//    NSString *str=@"1368082020";//时间戳
    NSTimeInterval time=[strTime doubleValue];      //因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
//    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setDateFormat:form_time];

    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    
    return currentDateStr;
}

//模板数据请
- (void)modelUrl_Http_Request:(NSString *)urlStr fileName:(NSString *)filename webview:(UIWebView *)webView {
    [self judgmentOfTheTemplate:filename andUrl:urlStr andWebView:webView];
}

- (void)intoTheWebViewData:(UIWebView *)webview andUrlStr:(NSString *)urlStr {
    NSURL *url = [[NSURL alloc] initWithString:urlStr];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [webview loadRequest:request];
}

//存模板本地
- (void)judgmentOfTheTemplate:(NSString *)fileName_Str andUrl:(NSString *)urlStr andWebView:(UIWebView *)webView {
 
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *path=[paths objectAtIndex:0];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:[path stringByAppendingPathComponent:fileName_Str]]) {
        [self intoTheWebViewData:webView andUrlStr:urlStr];
        [self saveTheData_Url:urlStr andfileName:fileName_Str];
        NSLog(@"没有模板");
    }else {
        
        [webView loadHTMLString:[self getDateFileAndTime:fileName_Str] baseURL:[NSURL URLWithString:@"http://192.168.1.254:8004"]];

        NSLog(@"有模板");
    }
}

//存数据
- (void)saveTheData_Url:(NSString *)Url_string andfileName:(NSString *)filename {
    
    NSString* htmlResponseStr=[NSString stringWithContentsOfURL:
                               [NSURL URLWithString:Url_string] encoding:NSUTF8StringEncoding error:Nil];

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *path=[paths objectAtIndex:0];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:[path stringByAppendingPathComponent:filename]]) {
        NSString *filepath = [path stringByAppendingPathComponent:filename];
        [fileManager createFileAtPath:filepath contents:nil attributes:nil];
        
        NSData* xmlData = [htmlResponseStr dataUsingEncoding:NSUTF8StringEncoding];
        
        [xmlData writeToFile:filepath options:0 error:nil];
        
        NSLog(@"%@",filepath);
        
        NSLog(@"%@",@"不存在就创建");
    }
}

//取数据
- (NSString *)getDateFileAndTime:(NSString *)fileName {
    
    NSString * sandBoxPath = NSHomeDirectory();
    NSString * documentPath = [sandBoxPath stringByAppendingPathComponent:@"Documents"];
    NSString * filename = [documentPath stringByAppendingPathComponent:fileName];
    NSString * appHtml = [NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",filename);
    return appHtml;
}

//JS数据注入
- (void)JS_datarequestinitWebView:(NSString *)data_str andData:(NSData *)data andwebView:(UIWebView *)webView {

        NSString* aStr= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSString *sddsd = [NSString stringWithFormat:@"%@(%@)",data_str,aStr];
        [webView stringByEvaluatingJavaScriptFromString:sddsd];

}

//拦截网络请求
- (BOOL) intercept_request_HTTP:(NSString *) intercept_Str {
     BOOL string;
    if ([intercept_Str rangeOfString:@"http://192.168.1.254:8004/pro/Home/station_news.html"].location != NSNotFound) {
        
        StandViewController *standViewController = [[StandViewController alloc]init];
        [self.navigationController pushViewController:standViewController animated:YES];
        
        string = @"NO";
    }else {
        string = @"YES";
    }
    
    return string;
}

//处理跳转
- (void) skip_view: (NSString *) skip_Str andintercept_Str: (NSString *)intercept_Str {
    StandViewController *standViewController = [[StandViewController alloc]init];

    if ([intercept_Str rangeOfString:skip_Str].location != NSNotFound) {
        return [self.navigationController pushViewController:standViewController animated:YES];
    }
//    return [self.navigationController pushViewController:standViewController animated:YES];
}

+ (BOOL)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
